package cn.xm.filter;

import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

public class RequestTimeFilter implements Order, GatewayFilter {

    // 手动获取log对象
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("path:{}",path);
        // 获取开始时间
        exchange.getAttributes().put("startTime",System.currentTimeMillis());
        // 回调
        return chain.filter(exchange).then(
            Mono.fromRunnable(() -> {
                // 开始时间
                Long startTime = exchange.getAttribute("startTime");
                // 结束时间
                Long endTime = (System.currentTimeMillis() - startTime);
                // 打印当前请求耗时
                log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
            })
        );

    }

    @Override
    public int value() {
        return 0;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
